<template>
    <div class="workflow-create">
        <el-steps :active="currentStep" finish-status="success">
            <el-step title="基本信息" />
            <el-step title="参数配置" />
        </el-steps>

        <div class="step-content">
            <WorkflowForm
                v-if="currentStep === 0"
                :workflow="workflowData"
                @next="handleNext"
                @cancel="handleCancel"
            />
            <WorkflowParams
                v-if="currentStep === 1"
                :workflow="workflowData"
                @prev="handlePrev"
                @save="handleSave"
            />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import WorkflowForm from '@/components/workflow/WorkflowForm.vue';
import WorkflowParams from '@/components/workflow/WorkflowParams.vue';
import { workflowApi } from '@/api/workflow';
import type { WorkflowTemplate } from '@/types';

const router = useRouter();
const currentStep = ref(0);
const workflowData = ref<Partial<WorkflowTemplate>>({
    name: '',
    description: '',
    category: '',
    tags: [],
    thumbnail: '',
    comfyuiJson: {},
    isPublic: false,
    version: '1.0.0',
    params: [],
    rows: 10
});

// 处理下一步
const handleNext = (data: Partial<WorkflowTemplate>) => {
    workflowData.value = { ...workflowData.value, ...data };
    currentStep.value = 1;
};

// 处理上一步
const handlePrev = () => {
    currentStep.value = 0;
};

// 处理取消
const handleCancel = () => {
    router.back();
};

// 处理保存
const handleSave = async (data: Partial<WorkflowTemplate>) => {
    try {
        // 合并并验证数据
        const finalData = {
            ...workflowData.value,
            ...data,
            params: Array.isArray(data.params) ? data.params : [],
            tags: Array.isArray(data.tags) ? data.tags : [],
            isPublic: Boolean(data.isPublic),
            rows: Number(data.rows) || 10
        };

        // 验证必要字段
        if (!finalData.comfyuiJson || typeof finalData.comfyuiJson !== 'object' || Object.keys(finalData.comfyuiJson).length === 0) {
            ElMessage.error('工作流配置不能为空');
            return;
        }
        if (!finalData.thumbnail) {
            ElMessage.error('预览图不能为空');
            return;
        }

        await workflowApi.createWorkflow(finalData);
        ElMessage.success('创建成功');
        router.push('/workflows');
    } catch (error) {
        ElMessage.error('创建失败');
        console.error('Create workflow error:', error);
    }
};
</script>

<style lang="scss" scoped>
.workflow-create {
    padding: 20px;

    .step-content {
        margin-top: 40px;
    }
}
</style> 